package cn.fzkj.springboot.advice;

import cn.fzkj.springboot.common.ResultData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @DESCRIPTION 结果统一封装
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper mapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        System.out.println("returnType  " + returnType);
        System.out.println("selectedContentType  " + selectedContentType);
        System.out.println("selectedConverterType.getName  " + selectedConverterType.getName());
        System.out.println("selectedConverterType.getTypeName  " + selectedConverterType.getTypeName());
        /**
         * 这块代码主要是为了当controller中方法返回值是String类型的时候，类型转换异常
         * 因为这里如果只返回ResultData类型的，controller中返回String类型的，就会报错
         */
        if (body instanceof String){
            try {
                return mapper.writeValueAsString(ResultData.success(body));
            } catch (JsonProcessingException e) {
            }
        }
        if (body instanceof ResultData){
            return body;
        }
        return ResultData.success(body);
    }
}
